<?php

namespace app\xwam\model;

/**
 * 推广链接 模型类
 *
 * @author SoChishun 2017-3-23
 */
class ReferralLinkModel extends AppbaseModel {

    protected $table = 't_user_referral';
    

    /**
     * 保存用户
     * @param int $admin_id 用户编号
     * @return array
     * @version 1.0 2015-3-6 by sutroon
     */
    public function saveUser($admin_id) {
        $validator = array(
            array('user_name', 'require', '用户名无效!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
            array('user_name', 'check_user_name', '用户名已被注册!', self::MUST_VALIDATE, 'callback', self::MODEL_INSERT),
            array('password', 'require', '密码无效!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
            array('status', 'number', '状态有误!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        );
        $is_edit = empty($_POST['id']) ? false : true;
        
        if (!$validate->scene($isAdd ? true : 'edit')->check($data)) {
            LogModel::saveUserOperate(false, sprintf('%s用户账户失败 user=%s, siteID=%d %s', ($is_edit ? '编辑' : '新增'), $data['user_name'], $data['siteID'], implode('; ', $this->getError())), $admin_id, ($is_edit ? LogModel::ACTION_EDIT : LogModel::ACTION_ADD));
            return xsfn_message(false, $validate->getError());
        }
        //图片上传
        $msg = \Common\Controller\UploadHandlerController::upload(array('savePath' => 'Face/', 'skipEmpty' => true));
        if (is_array($msg)) {
            $data['face_url'] = $msg['face_url']['filepath'];
        }
        $data = $this->data;
        if ($isAdd) {
            unset($data['id']);
            $this->type_name = 'ADMIN';
            $result = $this->isUpdate(false)->save($data);
        } else {
            unset($data['user_name']);
            $result = $this->isUpdate(true)->save($data);
        }
        LogModel::saveUserOperate($result, sprintf('%s用户账户%s user=%s', ($is_edit ? '编辑' : '新增'), '{%}', $data['user_name']), $admin_id, ($is_edit ? LogModel::ACTION_EDIT : LogModel::ACTION_ADD));
        return xsfn_message($result);
    }

    // 检测用户名是否重复 2016-4-8 SoChishun Added.
    function check_user_name($val) {
        $n = $this->where(array('user_name' => trim($val)))->count('id');
        return $n < 1;
    }

    /**
     * 删除用户
     * @param string $id 主键编号,多个之间以逗号隔开
     * @param int $admin_id 操作员编号
     * @return array
     * @version 1.0 2015-6-10 SoChishun Added.
     */
    public function delete_user($id, $admin_id) {
        if (!$admin_id) {
            return xsfn_message(false, '用户无效');
        }
        if (!$id) {
            return xsfn_message(false, '编号无效');
        }
        $result = $this->where(['id' => ['in', $id]])->delete();
        
        LogModel::saveUserOperate($status, "删除用户账户($id){%} $msg,操作员:$admin_id", $admin_id, LogModel::ACTION_DELETE);
        return xsfn_message($result);
    }
}
